import * as React from 'react';
import { findDOMNode } from 'react-dom';
import { Button, Table, Pagination, Icon, Form, Input, message } from 'antd';
import { IStackViewPros, renderViewByHash } from '../../component/common/StackView';
import LoadingComponent from '../../component/common/LoadingComponent';

import MyBread from '../../component/common/MyBread';
import QueryBar from '../../component/common/QueryBar';

import { RootHash, StackViewPages } from './Customer';
import CustomerStore, { PageInfo, PageData } from './CustomerStore';


export default class CustomerList extends LoadingComponent<IStackViewPros, any>{

  constructor(props: any) {
    super(props);
    this.state = Object.assign({
      scrollHeight: 400,
      selectedRowKeys: [],
      pageInfo: new PageInfo(1, 10),
      query: {},
    }, this.state);
    this.updateTableScroll = this.updateTableScroll.bind(this);
  }

  //  组件将要加载
  componentWillMount() {
    this.loadTable();
    window.addEventListener('resize', this.updateTableScroll);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateTableScroll);
  }

  componentDidMount() {
    super.componentDidMount();
    this.updateTableScroll();
  }

  updateTableScroll() {
    const scrollContentPanel = findDOMNode(this.refs['scrollContentPanel']);
    const scrollPaginationPanel = findDOMNode(this.refs['scrollPaginationPanel']);
    const scrollPaginationHeight = scrollPaginationPanel ? (scrollPaginationPanel.clientHeight + 16) : 48;
    const tableHeight = scrollContentPanel.clientHeight - 16 * 2 - scrollPaginationHeight;
    const scrollHeight = tableHeight - 48;
    this.setState({
      scrollHeight,
      tableHeight
    });
  }

  // create a new  item
  addItem = () => {
    this.props.stackView.pushView(renderViewByHash(StackViewPages, RootHash + '/add', {
      reload: () => {
        this.loadTable();
      }
    }));
  }
  // view item
  viewItem = (id: number) => {
    this.props.stackView.pushView(renderViewByHash(StackViewPages, RootHash + '/view/' + id, {
      reload: () => {
        this.loadTable();
      }
    }));
  }
  // delete
  deletItem = (id: string) => {
    CustomerStore.remove(id);
    this.loadTable();
  }

  // delete checked
  deleteChecked = () => {
    let {selectedRowKeys} = this.state;
    if (!selectedRowKeys || selectedRowKeys.length === 0) {
      return message.warn('请选择要操作的数据。');
    }
    Array.from(selectedRowKeys).map((id: string) => {
      CustomerStore.remove(id);
    });
    this.loadTable();
  }

  // load table data
  loadTable = (pageIndex: number = 1, pageSize?: number) => {
    let pageInfo: PageInfo = this.state.pageInfo;
    pageInfo.setPageIndex(pageIndex);
    if (pageSize !== undefined) {
      pageInfo.setPageSize(pageSize);
    }
    let pageData: PageData = CustomerStore.getPage(pageInfo);
    this.fetchLoad({
      pageData
    });
    this.setState({ 'selectedRowKeys': [] });
  }

  setQueryParam = (e: any, key: string) => {
    let state = Object.assign({}, this.state);
    let value: any = '';
    if (typeof e === 'object') {
      if (e.length >= 0) {
        //  数组
        value = e;
      } else {
        //  对象
        value = e.target.value;
      }
    } else {
      //  字符或者数字
      value = e;
    }
    // 条件变更
    state.query[key] = value;
    //  过滤掉空数组条件
    if (typeof value === 'object' && value.length === 0) {
      delete state.query[key];
    }
    this.setState(state);
  }

  search = () => {
    this.loadTable();
  }

  empty = () => {
    let pageInfo: PageInfo = this.state.pageInfo;
    pageInfo.setPageIndex(1);
    let pageData: PageData = new PageData(0);
    this.fetchLoad({
      pageData
    });
    this.setState({ 'selectedRowKeys': [] });
  }

  copy = () => {
    CustomerStore.copy();
    this.loadTable();
  }

  renderUI() {
    let {filteredInfo, sortedInfo, scrollHeight, tableHeight} = this.state;
    sortedInfo = sortedInfo || {};
    filteredInfo = filteredInfo || {};

    const COLUMNS = [{
      title: '序号',
      key: 'Index',
      dataIndex: 'Index',
      width: '40px',
      render: (text, record, index) => index + 1,
    }, {
      title: 'Id',
      key: 'Id',
      dataIndex: 'id',
      width: '60px',
      filteredValue: filteredInfo.name,
      onFilter: (value, record) => record.name.includes(value),
      sorter: (a, b) => a.name.length - b.name.length,
      sortOrder: sortedInfo.columnKey === 'name' && sortedInfo.order,
    }, {
      title: 'Email',
      key: 'email',
      dataIndex: 'email',
      width: 200,
      render: (text, record, index) => record.form2 && record.form2.fields && record.form2.fields.email,
    }, {
      title: 'NickName',
      key: 'nickName',
      dataIndex: 'nickName',
      width: 150,
      render: (text, record, index) => record.form2 && record.form2.fields && record.form2.fields.nickName,
    }, {
      title: 'Gender',
      key: 'Gender',
      dataIndex: 'Gender',
      width: 60,
      render: (text, record, index) => record.form2 && record.form2.fields && record.form2.fields.Gender,
    }, {
      title: 'Birthday',
      key: 'Birthday',
      dataIndex: 'birthday',
      width: 60,
      render: (text, record, index) => record.form2 && record.form2.fields && record.form2.fields.birthday,
    }, {
      title: 'Action',
      key: 'action',
      width: 60,
      render: (text, record) => (
        <span>
          <Icon type='eye' title='查看' onClick={() => this.viewItem(record.id)} />
          <span className='ant-divider' />
          <Icon className='ant-danger' type='delete' title='删除' onClick={() => this.deletItem(record.id)} />
        </span>
      ),
    }];
    const {pageData, selectedRowKeys} = this.state;

    const pagination = {
      current: this.state.pageInfo.pageIndex,
      total: pageData.total,
      pageSize: this.state.pageInfo.pageSize,
      showSizeChanger: true,
      onShowSizeChange: (current, pageSize) => {
        let {pageInfo} = this.state;
        pageInfo.pageSize = pageSize;
        this.setState({
          pageInfo
        });
        this.loadTable();
        console.log('Current: ', current, '; PageSize: ', pageSize);
      },
      onChange: (current) => {
        console.log('Current: ', current);
        this.loadTable(current);
      },
    };

    //  rowSelection object indicates the need for row selection
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        this.setState({ selectedRowKeys });
      },
    };

    return (
      <div>
        <Table style={{ height: tableHeight }} scroll={{ y: scrollHeight }} rowSelection={rowSelection} pagination={false} columns={COLUMNS} dataSource={pageData.items} bordered={true} rowKey={record => record['id']} />
        <div ref='scrollPaginationPanel' className='view__pagination flex-col'>
          <div className='select-info'>{`Selected ${selectedRowKeys.length} items`}</div>
          <div className='bat-button flex-grow-1'>
            <Button className='ant-btn-danger' icon='delete' onClick={this.deleteChecked}>批量删除</Button>
            <Button type='primary' icon='search' onClick={this.empty}>空数据</Button>
            <Button type='ghost' icon='copy' onClick={this.copy}>复制</Button>
          </div>
          <Pagination showSizeChanger {...pagination} />
        </div>
      </div>
    );
  }

  render() {
    return (
      <div className='view-inner flex-grow-1 flex-row'>
        <div className='view__banner flex-col'>
          <div className='flex-grow-1'>
            <MyBread stackView={this.props.stackView} endComponent={CustomerList} />
          </div>
          <div className='break-no'>
            <Button type='primary' icon='plus' onClick={this.addItem}>新建</Button>
          </div>
        </div>
        <div ref='scrollQueryPanel' className='view__query'>
          <QueryBar onSubmit={this.loadTable}>
            <QueryBar.Base>
              <Form.Item
                label='姓名/手机号码'
                className='query-item'
              >
                <Input
                  placeholder='请输入姓名/手机号码'
                  value={this.state.query.customerName}
                  onChange={(e) => { this.setQueryParam(e, 'customerName'); }} />
              </Form.Item>
              <Form.Item
                label='姓名/手机号码'
                className='query-item'
              >
                <Input
                  placeholder='请输入姓名/手机号码'
                  value={this.state.query.customerName}
                  onChange={(e) => { this.setQueryParam(e, 'customerName'); }} />
              </Form.Item>
              <Form.Item
                label='姓名/手机号码'
                className='query-item'
              >
                <Input
                  placeholder='请输入姓名/手机号码'
                  value={this.state.query.customerName}
                  onChange={(e) => { this.setQueryParam(e, 'customerName'); }} />
              </Form.Item>
              <div className='query-item break-no'>
                <button type='button' className='bui-link-btn expand-trigger' data-size-trigger>更多条件 <Icon type='circle-down' /></button>
                <Button type='ghost' icon='search' onClick={this.search}>查询</Button>
              </div>
            </QueryBar.Base>
            <QueryBar.Expand>
              <Form.Item
                label='姓名/手机号码'
                className='query-item'
              >
                <Input
                  placeholder='请输入姓名/手机号码'
                  value={this.state.query.customerName}
                  onChange={(e) => { this.setQueryParam(e, 'customerName'); }} />
              </Form.Item>
              <Form.Item
                label='姓名/手机号码'
                className='query-item'
              >
                <Input
                  placeholder='请输入姓名/手机号码'
                  value={this.state.query.customerName}
                  onChange={(e) => { this.setQueryParam(e, 'customerName'); }} />
              </Form.Item>
              <Form.Item
                label='姓名/手机号码'
                className='query-item'
              >
                <Input
                  placeholder='请输入姓名/手机号码'
                  value={this.state.query.customerName}
                  onChange={(e) => { this.setQueryParam(e, 'customerName'); }} />
              </Form.Item>
              <Form.Item
                label='姓名/手机号码'
                className='query-item'
              >
                <Input
                  placeholder='请输入姓名/手机号码'
                  value={this.state.query.customerName}
                  onChange={(e) => { this.setQueryParam(e, 'customerName'); }} />
              </Form.Item>
            </QueryBar.Expand>
          </QueryBar>

        </div>
        <div ref='scrollContentPanel' className='view__content view__content--table flex-grow-1 overflow-scroll relative'>
          {this.renderIf()}
        </div>
      </div>
    );
  }
}
